package org.springframework.samples.mvc.ajax.account;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
@RequestMapping(value = "/login")
public class Login {

	private static List<LoginAccount> accounts = new ArrayList<LoginAccount>();
	{
		LoginAccount a = null;
		for (int i = 0; i < 10; i++) {
			a = new LoginAccount();
			a.setLogin("login" + i);
			a.setPassword("pass" + i);
			accounts.add(a);
		}
	}

	@RequestMapping(method = RequestMethod.GET)
	public String getCreateForm(Model model) {
		return "login/login";
	}

	@RequestMapping(method = RequestMethod.POST)
	public String login(HttpServletRequest request,
			HttpServletResponse response,
			@RequestParam(value = "login") String login,
			@RequestParam(value = "password") String password) {
		LoginAccount a = new LoginAccount();
		a.setLogin(login);
		a.setPassword(password);
		List<Cookie> cookies = new ArrayList<Cookie>(Arrays.asList(request
				.getCookies()));
		String integration = "/";
		for (Cookie cookie : cookies) {
			if (cookie.getName().equals("integration")) {
				integration += cookie.getValue();
				break;
			}
		}
		if (accounts.contains(a)) {
			response.addCookie(new Cookie("loggedIn", "true"));
			response.addCookie(new Cookie("userId", login));
			return "redirect:" + integration + "/submissionPage.html?"
					+ request.getQueryString();
		}
		return "login/login";
	}
}
